import { onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'

export function useChart(options = {}) {
    const chartRef = ref(null)
    let chart = null

    onMounted(() => {
        if (chartRef.value) {
            chart = echarts.init(chartRef.value)
            options.init && options.init(chart)
        }
    })

    onUnmounted(() => {
        if (chart) {
            chart.dispose()
            chart = null
        }
    })

    const updateChart = (option) => {
        if (chart) {
            chart.setOption(option)
        }
    }

    return {
        chartRef,
        updateChart
    }
}